package com.sun.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.sun.listener.ControllerStudentListener;
import com.sun.listener.StudentListener;
import com.sun.pojo.Student;
import jdk.jfr.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("student")
public class StudentController {

    @Autowired
    ControllerStudentListener controllerStudentListener;

    @RequestMapping("read")
    @ResponseBody
    public String readExcel(MultipartFile file){

        try {
            ExcelReaderBuilder readWorkBook = EasyExcel.read(file.getInputStream(), Student.class, controllerStudentListener);
            ExcelReaderSheetBuilder sheet = readWorkBook.sheet();
            sheet.doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
        return "success";
    }

    @RequestMapping("write")
    @ResponseBody
    public void writeExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String filename = URLEncoder.encode("测试","UTF-8");
        response.setHeader("Content-Dispositon","attachment;filename*=UTF-8''"+filename+".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        //工作簿对象
        ExcelWriterBuilder writeWorkBook = EasyExcel
                .write(outputStream, Student.class);
        //工作表对象
        ExcelWriterSheetBuilder sheet = writeWorkBook.sheet();
        //写
        List<Student> studentList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            studentList.add(new Student("sxt","男",new Date(),i));
        }
        sheet.doWrite(studentList);
    }

}
